package com.example.boot.service;

import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.OS;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.lemon.core.base.util.ServletUtils;
import com.lemon.core.log.dto.OperateLogCreateDTO;
import com.lemon.core.log.events.OperateLogEvent;
import com.lemon.core.web.util.TracerUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 保存登录日志服务
 *
 * @author pan
 * @since 2019-03-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OptLogSaveService {

    private static final String USER_AGENT = "User-Agent";

    /**
     * 保存日志
     *
     * @param optLog
     */
    public boolean createLog(OperateLogCreateDTO optLog) {
        HttpServletRequest request = ServletUtils.getHttpServletRequest();
        String ua = request.getHeader(USER_AGENT);
        final UserAgent userAgent = UserAgentUtil.parse(ua);
        final Browser browser = userAgent.getBrowser();
        final OS os = userAgent.getOs();

        // 记录日志，实际存入数据库或者其他需自己实现
        log.info("ip: {}", ServletUtils.getClientIP(request));
        log.info("browser: {}", browser.getName());
        log.info("os: {}", os.getName());
        log.info("module: {}", optLog.getModule());
        log.info("param: {}", optLog.getRequestParam());
        return true;
    }

}
